#include "chinactprealtime.h"
#include <QDebug>

ChinactpRealtime::ChinactpRealtime(CThostFtdcMdApi *api, QObject *parent)
    : QObject(parent), m_api(api) {
    // 初始化登录信息（实际应用中从配置文件读取）
    gBrokerID[0] = '\0';
    gInvesterID[0] = '\0';
    gInvesterPassword[0] = '\0';
    qstrncpy(gBrokerID, "9999", 4);
    qstrncpy(gInvesterID, "123456", 6);
    qstrncpy(gInvesterPassword, "", 11);
}

void ChinactpRealtime::OnSetInstrument(QStringList m_instrumentList){
    instrumentList = m_instrumentList;
}

QStringList ChinactpRealtime::OnGetInstrument(){
    return instrumentList;
}

// 连接成功回调
void ChinactpRealtime::OnFrontConnected() {
    qDebug() << "行情服务器连接成功，开始登录...";
    emit connected();


    CThostFtdcReqUserLoginField loginReq{};
    // 安全复制BrokerID，检查长度避免溢出
    const size_t brokerIdMaxLen = sizeof(loginReq.BrokerID) - 1; // 预留终止符位置
    qstrncpy(loginReq.BrokerID, gBrokerID, brokerIdMaxLen);
    loginReq.BrokerID[brokerIdMaxLen] = '\0'; // 确保字符串终止

    // 安全复制UserID
    const size_t userIdMaxLen = sizeof(loginReq.UserID) - 1;
    qstrncpy(loginReq.UserID, gInvesterID, userIdMaxLen);
    loginReq.UserID[userIdMaxLen] = '\0';

    // 安全复制Password
    const size_t passwordMaxLen = sizeof(loginReq.Password) - 1;
    qstrncpy(loginReq.Password, gInvesterPassword, passwordMaxLen);
    loginReq.Password[passwordMaxLen] = '\0';


    int nRequestID = 1;
    m_api->ReqUserLogin(&loginReq, nRequestID);
}

// 断开连接回调
void ChinactpRealtime::OnFrontDisconnected(int nReason) {
    qDebug() << "行情服务器断开连接，原因：" << nReason;
    emit disconnected(nReason);
}

// 登录响应回调
void ChinactpRealtime::OnRspUserLogin(CThostFtdcRspUserLoginField *pRspUserLogin,
                           CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {
    bool success = (pRspInfo == nullptr || pRspInfo->ErrorID == 0);
    QString msg = success ? "登录成功" : QString("登录失败：%1 %2")
                                             .arg(pRspInfo->ErrorID).arg(pRspInfo->ErrorMsg);
    qDebug() << msg;
    emit loginResult(success, msg);

    if (success) {
        // 登录成功后订阅行情（示例：订阅螺纹钢主力合约）
        QStringList instruments = OnGetInstrument();
        int count = instruments.size();
        if(count > 0){
            char **ppInstrumentID = new char*[count];
            for (int i = 0; i < count; ++i) {
                ppInstrumentID[i] = new char[32];
                //strcpy(ppInstrumentID[i], instruments[i].toUtf8().data());
                qstrncpy(ppInstrumentID[i],instruments[i].toUtf8().data(),32);
            }

            // 订阅行情
            m_api->SubscribeMarketData(ppInstrumentID, count);

            // 释放内存
            for (int i = 0; i < count; ++i) {
                delete[] ppInstrumentID[i];
            }
            delete[] ppInstrumentID;

        }else{
            qDebug() << "没有订阅任何合约";
        }
    }
}

// 订阅行情响应
void ChinactpRealtime::OnRspSubMarketData(CThostFtdcSpecificInstrumentField *pSpecificInstrument,
                               CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {
    if (pRspInfo && pRspInfo->ErrorID != 0) {
        qDebug() << "订阅行情失败：" << pRspInfo->ErrorMsg;
    } else {
        qDebug() << "订阅行情成功：" << pSpecificInstrument->InstrumentID;
    }
}

// 接收行情数据（核心）
void ChinactpRealtime::OnRtnDepthMarketData(CThostFtdcDepthMarketDataField *pDepthMarketData) {
    if (pDepthMarketData) {
        // 提取合约代码和最新价
        QString instrumentID = pDepthMarketData->InstrumentID;
        double lastPrice = pDepthMarketData->LastPrice;
        double askPrice = pDepthMarketData->AskPrice1;
        double bidPrice = pDepthMarketData->BidPrice1;
        //qDebug() << "收到行情：" << instrumentID << "最新价：" << lastPrice;

        // 发送信号到主线程更新UI
        emit marketDataReceived(instrumentID, lastPrice,askPrice,bidPrice);
    }
}

// 错误信息回调
void ChinactpRealtime::OnRspError(CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {
    if (pRspInfo) {
        qDebug() << "错误信息：" << pRspInfo->ErrorID << pRspInfo->ErrorMsg;
    }
}
